<template>
  <div
    ref="mainRef"
    class="mainEcharts"></div>
</template>

<script lang="ts" setup>
import { init, type ECharts } from 'echarts'
import { onMounted, onUnmounted, ref } from 'vue'
import Debounce from '@/compoase/debounce'
import type { INV } from '@/types/echarts'
const mainRef = ref()
const props = defineProps<{
  options: INV[];
}>()
// 初始化Echarts
let myChart: ECharts | null = null
const initEchart = () => {
  myChart === null && (myChart = init(mainRef.value))
  const option = {
    color: [
      '#29F1FA',
      '#2886F4',
      '#627BA1',
      '#F34336',
      '#ee6666',
      '#73c0de',
      '#3ba272',
      '#fc8452',
      '#9a60b4',
      '#ea7ccc'
    ],
    tooltip: {
      trigger: 'item'
    },
    legend: {
      bottom: 0,
      itemGap: 20,
      textStyle: {
        color: '#fff'
      },
      data: [{ name: '正常' }, { name: '等待' }, { name: '离线' }, { name: '故障' }]
    },
    series: [
      {
        name: '逆变器状态',
        type: 'pie',
        bottom: 20,
        label: {
          show: true,
          color: '#fff',
          formatter(param: any) {
            // correct the percentage
            return param.name + ' (' + param.percent + '%)'
          }
        },
        radius: ['40%', '70%'],
        data: props.options
      }
    ]
  }
  myChart.setOption(option)
}
onMounted(() => {
  initEchart()
})

const debounce = new Debounce()
const resize = debounce.use(() => {
  myChart?.resize()
})
const listener = () => {
  resize()
}
window.addEventListener('resize', listener, { passive: false })
onUnmounted(() => {
  window.removeEventListener('resize', listener)
})
</script>

<style lang="scss" scoped>
.mainEcharts {
  height: calc(100% - 4.1rem - 2px);
  padding-left: 10px;
}
</style>
